package com.PopFax;


import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;


public class Bean  extends Activity implements Runnable,View.OnClickListener{

	
	EditText userName;
	EditText password;
    Button btnSignIn;
    private ProgressDialog pd ;
    CheckBox check1;
    String finalResult="";
    View view ;
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main); 
	        
	        SQLiteDatabase myDB= null; 
	 		  String TableName = "store"; 
	  myDB = this.openOrCreateDatabase("storage", MODE_PRIVATE, null); 
	 		  myDB.execSQL("CREATE TABLE IF NOT EXISTS " 
	 	 		     + TableName 
	 	 		     + " (username VARCHAR, password VARCHAR);"); 
	 		  
	 		 Cursor c = myDB.rawQuery("SELECT username FROM " + TableName , null); 
	 		 
	 	
	 		   int x=c.getCount();
	 		   System.out.println(x+"jkjkklldfvkjkldjklljkljkljkljkljkljkljkl");
	 		 
	 		 
	 		    
	 		     if(x==2){
	 		    	   
	 		        userName=(EditText)findViewById(R.id.userName);
	 		     
	 		        password=(EditText)findViewById(R.id.password);
	 		        btnSignIn=(Button)findViewById(R.id.btnSighIn);
	 		        check1 = (CheckBox) findViewById(R.id.check1);
	 		        btnSignIn.setOnClickListener(this);
	 		        
	 		     }
	 		     else {
	 		    	// pd = ProgressDialog.show(this, "Logging In..", "Authenticating..", true,false);
//	 		    	login();
 		    	   Intent mIntent = new Intent(view.getContext(),loginBox.class);
			    	startActivity(mIntent);
	 		    	   
	 		    	 
	 		     }
	 		    }
	 		   
	      /* public void login(){
	    	   pd.dismiss();
	    	
	    	   
	    	   
	    	   
	       }*/
	     
	        
	        
	   

	 
	 
	    	public void onClick(View v)
        	{
	    			
	    	
	 		 pd = ProgressDialog.show(this, "Logging In..", "Authenticating..", true,false);
	 		   // Check if our result was valid. 
	 		 	database();    
	 			Thread thread = new Thread(this);
	 			thread.start();
	 				               
        	}
	 	public void database(){

	 		 if(check1.isChecked()){
	 		 
	 		SQLiteDatabase myDB= null; 
	 		  String TableName = "store"; 
	 		  
	 		  String Data = ""; 
	 		  
	 		  /* Create a Database. */ 
	 		   
	 		   myDB = this.openOrCreateDatabase("storage", MODE_PRIVATE, null); 
	 		  
	 		   /* Create a Table in the Database. */ 
	 		   myDB.execSQL("CREATE TABLE IF NOT EXISTS " 
	 		     + TableName 
	 		     + " (username VARCHAR, password VARCHAR);"); 
	 		  
	 		   /* Insert data to a Table*/ 
	 		   myDB.execSQL("INSERT INTO " 
	 		     + TableName 
	 		     + " (username,password)" 
	 		     + " VALUES ('"+userName.getText().toString()+"','"+ password.getText().toString()+"');"); 
	 		  
	 		   /*retrieve data from database */ 
	 		   Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null); 
	 		
	 		 
	 		   int Column1 = c.getColumnIndex("username"); 
	 		   int Column2 = c.getColumnIndex("password"); 
	 		   c.moveToLast(); 
	 		   if (c != null) { 
	 		    // Loop through all Results 
	 		    do { 
	 		     String word1 = c.getString(Column1); 
	 		     String word2 = c.getString(Column2); 
	 		     Data =Data +word1+"/"+word2+"\n";
	 		     System.out.println(Data);
	 		    }while(c.moveToNext());
	 		   }
	 		   
	 		  myDB.close();
	 		 }
	 		
	 	}
	 
	 
	 

	 
	



public void run() {
	try {
        HashMap<String,String> data= new HashMap<String, String>();
		data.put("action","retrieve_incoming_fax_list");
		data.put("username",userName.getText().toString());
	//data.put("username","udeep.m@gmail.com");
		data.put("password",password.getText().toString());
		data.put("dateFrom","2010-04-01 01:00:00");
		data.put("dateTo","2010-04-05 23:00:00");
		//data.put("password","nnn3wj4n");
	
	InputStream toastData= (doSubmit("https://api.popfax.com/api-server.php", data));
    
		/* Get a SAXParser from the SAXPArserFactory. */ 
    SAXParserFactory spf = SAXParserFactory.newInstance(); 
    SAXParser sp = spf.newSAXParser(); 

    /* Get the XMLReader of the SAXParser we created. */ 
    XMLReader xr = sp.getXMLReader(); 
    /* Create a new ContentHandler and apply it to the XML-Reader*/ 
    ExampleHandler myExampleHandler = new ExampleHandler(); 
    xr.setContentHandler(myExampleHandler); 
     
    /* Parse the xml-data from our URL. */ 
    xr.parse(new InputSource(toastData)); 
    /* Parsing has finished. */ 

    /* Our ExampleHandler now provides the parsed data to us. */ 
    ParsedExampleDataSet parsedExampleDataSet = 
                                  myExampleHandler.getParsedData(); 

    /* Set the result to be displayed in our GUI. */ 
    
    
    if((parsedExampleDataSet.intReturn()==0))
    {
    	finalResult="Logged In Successfully";
    	
    	//Intent mIntent = new Intent(v.getContext(),loginBox.class);
    	//startActivity(mIntent);
    	 
    	 
    }else if ((parsedExampleDataSet.intReturn()==107))
    {
    	finalResult="UserName/Password Invalid";
//    	Toast.makeText(getApplicationContext(),finalResult, Toast.LENGTH_SHORT).show();
    }else
    {
    	finalResult="Other Error";
//    	Toast.makeText(getApplicationContext(),finalResult, Toast.LENGTH_SHORT).show();
    }
    
		
     }catch(Exception e)
     {
     	e.printStackTrace();
     }


        handler.sendEmptyMessage(0);
	        

}




private Handler handler = new Handler() {
       
        public void handleMessage(Message msg) {
                pd.dismiss();
                Toast.makeText(getApplicationContext(),finalResult, Toast.LENGTH_SHORT).show();
                if(finalResult.equals("Logged In Successfully"))
                {
                	Intent mIntent = new Intent(view.getContext(),loginBox.class);
     		    	startActivity(mIntent);
                }
                

        }
};



public InputStream doSubmit(String url, HashMap <String,String> data)throws Exception{
	
	
	try{
	
	URL siteUrl= new URL(url);
	HttpURLConnection conn= (HttpURLConnection)siteUrl.openConnection();
	conn.setRequestMethod("POST");
	conn.setDoOutput(true);
	conn.setDoInput(true);
	DataOutputStream dataOutputStream=new DataOutputStream(conn.getOutputStream());
	
	Set keys=data.keySet();
	Iterator iter= keys.iterator();
	String content="";
	for(int m=0;iter.hasNext();m++){
		Object key=iter.next();
		if(m!=0)
		{
			content +="&";
	}
		content +=key+"="+URLEncoder.encode(data.get(key),"UTF-8");
	}
	
	
	
	dataOutputStream.writeBytes(content);
	dataOutputStream.flush();
	dataOutputStream.close();
	
	/*
	BufferedReader bufferedReader= new BufferedReader(new InputStreamReader (conn.getInputStream()));
	String line="";
	String retLine = "";
	while ((line=bufferedReader.readLine())!= null){
		System.out.println(line);
		retLine = retLine + line;
	}
	
	bufferedReader.close();*/
	return conn.getInputStream();
	
}catch(Exception e){
	e.printStackTrace();
	return null;
}
}





}





















